package com.pxdp.service.impl;

import cn.hutool.extra.expression.ExpressionException;
import cn.hutool.json.JSONUtil;
import com.pxdp.entity.ShopType;
import com.pxdp.mapper.ShopTypeMapper;
import com.pxdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> cacheToList() {
        //查询redis中是否有数据
        List<String> JsonShoptype = stringRedisTemplate.opsForList().range(RedisConstants.SHOP_TYPE_NAME,0,10);
        //如果不为空 直接返回数据
        if(!JsonShoptype.isEmpty()){
            List<ShopType> list = new ArrayList<>();
            for (String str : JsonShoptype) {
                list.add(JSONUtil.toBean(str, ShopType.class));
            }
            return list;
        }
        //如果为空 查询数据库并添加到缓存
        List<ShopType> shoptypesList = query().orderByAsc("sort").list();

         if(shoptypesList.isEmpty()){
             throw new ExpressionException("没有查询到信息");
         }
        for (ShopType shopType : shoptypesList) {
            stringRedisTemplate.opsForList().rightPush(RedisConstants.SHOP_TYPE_NAME, JSONUtil.toJsonStr(shopType));
        }

        return shoptypesList;
    }
}
